﻿using MQTTnet.Server;

namespace MQTTServer
{
internal class Program
{
    static async Task Main(string[] args)
    {
        await InitServer();
    }
    static async Task InitServer()
    {
        var mqttServerOptions = new MqttServerOptionsBuilder()
            .WithDefaultEndpoint()
            .Build();

        var mqttServer = new MqttServerFactory().CreateMqttServer(mqttServerOptions);

        //客户端连接事件
        mqttServer.ClientConnectedAsync += e =>
        {
            Console.WriteLine($"客户端 {e.ClientId} 连接成功......");
            return Task.CompletedTask;
        };

        //客户端断开连接事件
        mqttServer.ClientDisconnectedAsync += e =>
        {
            Console.WriteLine($"客户端 {e.ClientId} 断开连接......");
            return Task.CompletedTask;
        };

        //客户端发布消息事件,客户端每次
        mqttServer.InterceptingPublishAsync += e =>
        {
            Console.WriteLine($"客户端 senderid:{e.ClientId} 发布消息:{e.ApplicationMessage.Topic}......");
            return Task.CompletedTask;
        };

        //客户端订阅主题事件
        mqttServer.ClientSubscribedTopicAsync += e =>
        {
            Console.WriteLine($"客户端 {e.ClientId} 订阅事件 :{e.TopicFilter.Topic}......");
            return Task.CompletedTask;
        };

        //客户端取消订阅事件
        mqttServer.ClientUnsubscribedTopicAsync += e =>
        {
            Console.WriteLine($"客户端 {e.ClientId} 取消订阅事件 :{e.TopicFilter}......");
            return Task.CompletedTask;
        };

        await mqttServer.StartAsync();
        Console.WriteLine("MQTT server 启动成功......");

        Console.WriteLine("按下任意键退出......");
        Console.ReadKey();

        await mqttServer.StopAsync();
    }
}
}
